//
//  HTVideoFilter.m
//  LiveStreaming
//
//  Created by N17 on 2021/2/18.
//  Copyright © 2021 Agora. All rights reserved.
//

#import "HTVideoFilter.h"
//todo --- HTEffect start4 ---
#import "HTUIManager.h"
#import <HTEffect/HTEffectInterface.h>
bool is_Mirror = true;
//todo --- HTEffect end ---

@implementation HTVideoFilter

- (instancetype)init {
    if (self = [super init]) {
    }
    return self;
}

- (void)dealloc {
    //todo --- HTEffect start6 ---
    [[HTEffect shareInstance] releaseBufferRenderer];
    [[HTUIManager shareManager] destroy];
    //todo --- HTEffect end ---
}

#pragma mark - StreamingKit AgoraVideoFilter Delegate
- (CVPixelBufferRef)process:(CVPixelBufferRef)inputPixelBuffer {
    //todo --- HTEffect start5 ---
    CVPixelBufferLockBaseAddress(inputPixelBuffer, 0);
    HTFormatEnum format;
    switch (CVPixelBufferGetPixelFormatType(inputPixelBuffer)) {
        case kCVPixelFormatType_32BGRA:
            format = HTFormatBGRA;
            break;
        case kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange:
            format = HTFormatNV12;
            break;
        case kCVPixelFormatType_420YpCbCr8BiPlanarFullRange:
            format = HTFormatNV12;
            break;
        default:
            NSLog(@"错误的视频帧格式！");
            format = HTFormatBGRA;
            break;
    }
    int imageWidth = 0;
    int imageHeight = 0;
    if (format == HTFormatBGRA) {
        imageWidth = (int)CVPixelBufferGetBytesPerRow(inputPixelBuffer) / 4;
        imageHeight = (int)CVPixelBufferGetHeight(inputPixelBuffer);
    } else {
//        imageWidth = (int)CVPixelBufferGetWidthOfPlane(inputPixelBuffer , 0);
        //如果出现花屏，修改imageWidth的获取方式
        imageWidth = (int)CVPixelBufferGetBytesPerRowOfPlane(inputPixelBuffer , 0);
        imageHeight = (int)CVPixelBufferGetHeightOfPlane(inputPixelBuffer , 0);
    }
    unsigned char *baseAddress = (unsigned char *)CVPixelBufferGetBaseAddressOfPlane(inputPixelBuffer, 0);
    
    CVPixelBufferUnlockBaseAddress(inputPixelBuffer, 0);
    
    if (!_isRenderInit) {
        [[HTEffect shareInstance] releaseBufferRenderer];
        _isRenderInit = [[HTEffect shareInstance] initBufferRenderer:format width:imageWidth height:imageHeight rotation:HTRotationClockwise0 isMirror:is_Mirror maxFaces:5];
    }
    [[HTEffect shareInstance] processBuffer:baseAddress];
    //todo --- HTEffect end ---
    
    return inputPixelBuffer;
    
}

@end
